package com.mypackage {

	import org.molamil.acto.core.loggers.Logger;
	import flash.text.TextField;
	import flash.events.MouseEvent;
	import flash.events.Event;
	import org.molamil.acto.core.events.ConfLoadEvent;
	import org.molamil.acto.App;
	import flash.display.MovieClip;
	/**
	 * @author Jorge Hernandez
	 */
	public class Index extends MovieClip {
		
		
		// CLASSPATH
		
		// Create a reference to the frontpage so it gets compiled into the SWF and is available
		// as a definition target on the acto.xml
		Frontpage;
		
		
		// PROPERTIES
		
		// Reference for the Acto application controller.
		private var _app:App;
		
		
		// CONSTRUCTOR
		
		public function Index() {
			
			trace("Hello Index!");
			
			// Create a new Acto App and pass this as the root display object for the application,
			// all views will take this as teh root of the display list.
			_app = new App(this);

			// Set the Acto logger to display info messages.
			Logger.level = Logger.LEVEL_INFO;
			
			init();
			
		}
		
		
		// PUBLIC METHODS
		
		public function init():void {
			
			// Add listeners for the configuration load.
			_app.addEventListener(ConfLoadEvent.COMPLETE, confCompleteHandler, false, 1, true);
			_app.addEventListener(ConfLoadEvent.ERROR, confErrorHandler, false, 0, true);
			
			// Load the configuration from the XML file.
			_app.loadConf("acto.xml");
			
			// Set up the contact button click handler.
			getChildByName("contactButton").addEventListener(MouseEvent.CLICK, contactClickHandler, false, 1, true);
			
		}



		// EVENT HANDLERS

		private function confCompleteHandler(event:ConfLoadEvent):void {
			
			// Dispatch an event that will be listened by a handler on acto.xml to display the frontpage.
			// Since the page has type Definition, it will create an instance from the class name defined as target.
			dispatchEvent(new Event("siteLoaded"));
			
		}
		
		private function confErrorHandler(event:ConfLoadEvent):void {
			trace("OOPS. Couldn't load the Acto configuration file.");
		}
		
		private function contactClickHandler(event:MouseEvent):void {
			
			var email:String = TextField(getChildByName("emailField")).text;
			
			// Dispatch a custom event when the contact button is clicked.
			// The command configured in acto.xml will listen to this event type and, since it is a RemoteCommand,
			// will call to the URL defined on the target property passing the email parameter.
			// The type of the command can be any class that implements an execute() method.
			dispatchEvent(new ContactEvent(ContactEvent.CONTACT_BUTTON_CLICK, email));
			
		}

		
	}
	
}
